<template>
	<div class="channels-box" v-if="channels.length > 0">
		<div class="news-types" :class="{ collapse: !isCollapse }">
			<div
				class="item"
				v-for="item in showChannels"
				:key="item.channelId"
				:class="{ active: chooseId === item.channelId }"
				@click="switchTo(item.channelId)"
			>
				<span class="name" v-text="item.name"></span>
			</div>
		</div>
		<!-- 折叠展开按钮 -->
		<div class="collapse-btn" @click="collapse">
			<i class="fa fa-chevron-down" :class="{ rotate180: !isCollapse }"></i>
			<span v-text="isCollapse ? '展开' : '折叠' "></span>
		</div>
	</div>
</template>

<script>
export default {
	data() {
		return {
			showChannels: [], // 要展示的频道
			isCollapse: true, // 当前是否为折叠状态
			chooseId: null,
		};
	},
	computed: {
		channels() {
			return this.$store.state.channels.data;
		}
	},
	methods: {
		switchTo(chooseId) {
			let index = this.channels.findIndex((item) => {
				return chooseId === item.channelId;
			});
			if (index < 6) {
				this.showChannels = this.channels.slice(0, 7);
			} else if (index + 7 > this.channels.length) {
				this.showChannels = this.channels.slice(this.channels.length - 7);
			} else {
				this.showChannels = this.channels.slice(index - 3, index + 4);
			}
			this.chooseId = chooseId;
			this.isCollapse = true;
			this.$emit('change', this.chooseId);
		},
		collapse() {
			this.isCollapse = !this.isCollapse;
			if (!this.isCollapse) {
				this.showChannels = this.channels;
			}
		},
	},
	watch: {
		channels: {
			immediate: true,
			handler() {
				if (this.channels.length > 0) {
					this.showChannels = this.channels.slice(0, 10);
					this.chooseId = this.showChannels[0].channelId;
					this.switchTo(this.chooseId);
				}
			}
		}
	}
};
</script>

<style scoped>
@import url(//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css);

.channels-box {
	display: flex;
	padding-bottom: 10px;
	border-bottom: 1px solid;
	position: relative;
}
.news-types {
	display: flex;
	flex-wrap: wrap;
	width: 95%;
	height: 50px;
	overflow: hidden;
	white-space: nowrap;
	position: relative;
}
.collapse {
	height: auto;
}
.news-types .item {
	border: 1px solid rgba(0, 0, 0, 0.4);
	padding: 8px 20px;
	margin: 10px 20px 10px 0;
	text-align: center;
	border-radius: 10px;
	cursor: pointer;
	transition: 0.5s;
}
.news-types .item:hover {
	background-color: #e1e1e1;
}
.news-types .item.active {
	background-color: #000;
	color: #ffffff;
}

/* 折叠展开按钮 */
.collapse-btn {
	height: 40px;
	line-height: 40px;
	cursor: pointer;
	color: #0069d9;
	position: absolute;
	right: 0;
	top: 10px;
}
.collapse-btn i {
	transition: 0.5s;
}
.rotate180 {
	transform: rotate(180deg);
}
</style>
